<template>
  <div class="common-list-container__v2" v-loading.fullscreen.lock="loading">
    <!--s 头部搜索栏 -->
    <div class="common-list-header__v2" ref="tableHeaderContainer">
      <div>
        <el-input class="search-input" placeholder="请输入工单编号/客户信息" v-model="searchParams.keyword">
          <el-button class="search-input__append" slot="append" @click="search">搜索</el-button>
        </el-input>
        <el-button type="plain-third" class="ml_12" @click="resetParams">重置</el-button>
      </div>
      <advanced-search 
        ref="popperAdvancedSearchRef"
        :fields="advanceSearchColumn" 
        :has-create="false"
        :has-save="false"
        :in-common-use="inCommonUse"
        @search="handleAdvancedSearch" 
        @reset="handleReset"
        @changeCommonUse="changeCommonUse"
      >
      </advanced-search>
    </div>
    <!--e 头部搜索栏 -->
    <!--s 内容 -->
    <div class="common-list-view__v2 mt_12">
      <div class="common-list-view-header__v2" ref="tableDoContainer">
        <div>
          <el-tooltip effect="dark" content="将待指派工单生成周期性计划任务" placement="bottom">
            <el-button v-if="showPlanTask" type="primary" @click="planTaskCreateDialogOpen">计划任务</el-button>
          </el-tooltip>
          <el-button type="primary" @click="allotMapDialogOpen">地图派单</el-button>
          <el-button type="primary" @click="batchAllotDialogOpen">批量指派</el-button>
          <el-tooltip effect="dark" content="当前视图有新工单时，请通知我" placement="top">
            <i
              class="iconfont icon-dingyuetongzhiguanli ml_20 pointer"
              :class="hasSub && 'actived'"
              @click="toggleTaskSubscribe">
              {{ hasSub ? '已订阅': '未订阅'}}
            </i>
          </el-tooltip>
        </div>
        <span class="el-dropdown-link cur-point mar-l-12" @click="showAdvancedSetting">
          选择列
          <i class="iconfont icon-fdn-select"></i>
        </span>
      </div>
      <!-- 已勾选项 -->
      <div
        class="common-list-selection__v2 mt_8"
        ref="tableFilterContainer"
      >
        <base-selection-bar
          ref="baseSelectionBar"
          v-model="multipleSelection"
          @toggle-selection="toggleSelection"
          @show-panel="showSelectionPanel"
        />
        <base-selection-panel
          ref="selectionPanel"
          :columns="[{label: '工单编号',prop: 'taskNo'},{label: '工单类型',prop: 'templateName'}]"
          :data="multipleSelection"
          :table-ref="$refs.multipleTable"
          @toggleSelection="toggleSelection"
          @change="(data) => multipleSelection = data">
        </base-selection-panel>
      </div>
      {{tableContainerHeight}}
      <!--s 表格 -->
      <el-table
        ref="multipleTable"
        class="common-list-table__v2 mt_8"
        stripe
        :data="taskPage.list"
        :highlight-current-row="false"
        :border="true"
        @select="handleSelection"
        @select-all="handleSelection"
        @sort-change="sortChange"
        header-row-class-name="common-list-table-header__v2"
        :height="tableContainerHeight"
      >
        <el-table-column
          type="selection"
          width="48"
          align="center"
          class-name="select-column"
        ></el-table-column>
        <el-table-column
          v-for="column in columns"
          v-if="column && column.show"
          show-overflow-tooltip
          :align="column.align"
          :key="column.field"
          :label="column.displayName"
          :min-width="column.minWidth"
          :prop="column.field"
          :sortable="column.sortable"
          :width="column.width"
          :resizable="true"
        >
          <template slot-scope="scope">
            <template v-if="column.renderCell">
              <base-table-cell :render-cell="column.renderCell" :column="column" :row="scope.row"></base-table-cell>
            </template>
            <template v-else>
              {{ $formatFormField(column, scope.row) }}
            </template>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          label="操作">
          <template slot-scope="scope">
            <el-button 
              :disabled="scope.row.inApprove == 1"
              type="text"
              @click="allotTask(scope.row)">
              指 派
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--e 表格 -->
      <!--s 分页信息 -->
      <div class="common-list-table-footer__v2 mt_12" ref="tableFooterContainer">
        <el-pagination
          background
          hide-on-single-page
          :page-sizes="defaultTableData.defaultPageSizes"
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-size="searchParams.pageSize"
          :current-page="searchParams.page"
          :layout="defaultTableData.defaultLayout"
          :total="taskPage.totalElements"
        >
        </el-pagination>
      </div>
      <!--e 分页信息 -->
    </div>
    <!--e 内容 -->

    <!-- 选择列 --> 
    <biz-select-column ref="advanced" @save="saveColumnStatus" />
    <!-- 计划任务弹窗 --> 
    <plan-task-edit-form :origin-form="planForm" :task-config="taskConfig" @submit="submitWithPlanTask" ref="planTaskEditForm">
    </plan-task-edit-form>
    <!-- 批量指派弹窗 -->
    <batch-allot-dialog ref="batchAllotDialog" :task-id-list="taskIds" />
    <!-- 地图派单 -->
    <allot-map-dialog ref="allotMapDialog" :task-id-list="taskIds" :advanced-search-params="{...advancedSearchParams, keyword: searchParams.keyword,}" :task-config="taskConfig"/>
  </div>
</template>

<script>
// utils
import _ from 'lodash';
import { defaultTableData } from '@src/util/table'
// api
import * as TaskApi from '@src/api/TaskApi';
// model
import Page from '@model/Page';
import {getColumnFields, getAdvancedFields} from './fields';
import TaskConfig from '@model/config/TaskConfig.ts'
// components
import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
import BaseTableCell from 'packages/BaseTableCell';
import BatchAllotDialog from './components/BatchAllotDialog/BatchAllotDialog.vue';
import AllotMapDialog from './components/AllotMapDialog/AllotMapDialog.vue';
import PlanTaskEditForm from './components/PlanTaskEditForm/PlanTaskEditForm.vue';

import formatColumn from 'packages/BaseTableCell/formatColumn';

import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'

const MAXCHECK = 500;

export default {
  name: 'task-allot-list',
  data() {
    return {
      defaultTableData,
      hasSub: false,
      showPlanTask: false,
      currentTaskType: {},
      taskTypes: [],
      taskFields: [],
      multipleSelection: [],

      planForm: {},
      taskConfig: {},

      searchParams: {
        keyword: '',
        pageSize: 10,
        page: 1,
        sorts: []
      },
      advancedSearchParams: {},
      taskPage: new Page(),

      visible: false,
      columns: getColumnFields(this),
      columnNum: 1,

      loading: false,
      // tableContainerHeight:'440px'
    }
  },
  computed: {
    /** 高级搜索字段 */
    advanceSearchColumn() {
      return [
        ...getAdvancedFields(this),
        ...this.taskFields.filter(filed => { // 过滤重复项
          return !getColumnFields(this).some(item => item.field === filed.fieldName);
        })
      ].filter(item => 
        item.isSearch && item.isSearch == 1
      );
    },
    taskIds() {
      return this.multipleSelection.map(item => item.id);
    },
    taskTypeList() {
      return [
        {
          name: '全部', id: ''
        },
        ...this.taskTypes
      ]
    },
    serviceTypeDataSource() {
      let field = this.taskFields.find(f => {
        if(f.fieldName === 'serviceType') return true;
        return false;
      }) || {};
      
      let dataSource = field?.setting?.dataSource || [];
      return [{text: '全部', value: ''}, ...dataSource];
    },
    serviceContentDataSource() {
      let field = this.taskFields.find(f => {
        if(f.fieldName === 'serviceContent') return true;
        return false;
      }) || {};
      
      let dataSource = field?.setting?.dataSource || [];
      return [{text: '全部', value: ''}, ...dataSource];
    },
    levelDataSource() {
      let field = this.taskFields.find(f => {
        if(f.fieldName === 'level') return true;
        return false;
      }) || {};
      
      let dataSource = field?.setting?.dataSource || [];
      return [{text: '全部', value: ''}, ...dataSource];
    }
  },
  watch: {
    taskFields() {
      this.columns = [
        ...getColumnFields(this),
        ...this.taskFields.filter(f => {
          return f.isSystem !== 1 
          && !['attachment', 'separator', 'info', 'autograph'].includes(f.formType)
        })
      ].map(field => {
        return {
          ...formatColumn(field),
          field: field.field || field.fieldName
        }
      });
    },
    'currentTaskType.id': {
      handler(newVal, oldVal) {
        if(newVal && newVal != oldVal) {
          this.fetchTaskFields();
        }
      }
    }
  },
  methods: {
    /** 打开已选panel */
    showSelectionPanel() {
      this.$refs.selectionPanel.openPanel();
    },
    /** 打开高级搜索 */
    panelSearchAdvancedToggle() {
      window.TDAPP.onEvent('pc：工单指派列表-高级搜索事件');
      this.visible = true;
    },
    /** 关闭高级搜索弹框 */
    closeDrawer(){
      this.visible = false;
    },
    resetParams () {
      const fromId = window.frameElement.getAttribute('id');
      this.$platform.refreshTab(fromId);
    },
    /**
     * @description 获取工单字段列表
     * @return {Promise}
     */
    fetchTaskFields() {
      let params = {
        typeId: this.currentTaskType.id || '',
        tableName: 'task',
        isFromSetting: false
      };
      TaskApi.getAllFields(params).then((result) => {
        result.forEach((field) => {
          field.group = 'task';
          field.label = field.displayName;
          field.field = field.fieldName;
          field.show = true;
        });
        this.taskFields = result;
      }).catch(err => {
        console.error(err);
      });
    },
    fetchInitData() {
      TaskApi.getAllotListInit()
        .then(res=> {
          let {taskTypeList = [], hasSub, showPlanTask} = res;
          this.showPlanTask = showPlanTask;
          this.hasSub = hasSub;
          this.taskTypes = taskTypeList;
        })
        .catch(err => console.error(err));
    },
    /** 获取列表数据 */
    fetchAllotList(searchParams) {
      let params = {
        ...this.searchParams,
        ...searchParams
      }

      console.log('搜索参数: ', params);

      this.loading = true;
      TaskApi.getTaskAllotList(params)
        .then((res) => {
          this.loading = false;
          if(!res.success) {
            return this.$platform.alert(res.message);
          }

          this.taskPage = res.result || {};
          this.taskPage.list = res.result.content;

          // 把选中的匹配出来
          if (this.multipleSelection.length) {
            this.$nextTick(() => {
              this.multipleSelection.forEach(item => {
                this.taskPage.list.forEach(v => {
                  if (v.id === item.id) {
                    this.$refs.multipleTable.toggleRowSelection(v);
                  }
                })
              })
            })
          }
        })
        .catch(err => {
          this.loading = false;
          console.error(err);
        })
    },
    /** 搜索事件 */
    search () {
      // 获取高级搜索参数
      let advancedSearchParams = this.$refs.searchPanel ? this.$refs.searchPanel.buildParams() : {};
      if(advancedSearchParams.taskType) {
        let typeId = advancedSearchParams.taskType;
        let taskType = this.taskTypes.find(item => item.id === typeId);
        this.currentTaskType = {
          id: typeId,
          name: taskType && taskType.name
        };
        advancedSearchParams.templateId = typeId;
      }
      let {customer, tlmName, area = {}, product, createUser = [] } = advancedSearchParams;
      advancedSearchParams = {
        ...advancedSearchParams,
        customerId: customer || '',
        customerLinkman: tlmName || '',
        cusCountry: area.country || '',
        cusProvince: area.province || '',
        cusDist: area.dist || '',
        cusCity: area.city || '',
        cusAddress: area.address || '',
        productId: product,
        createUserIds: createUser,
      }
      this.advancedSearchParams = advancedSearchParams;

      this.fetchAllotList(advancedSearchParams);
      this.closeDrawer();
    },
    /** 打开选择列 */
    showAdvancedSetting(){
      window.TDAPP.onEvent('pc：指派工单列表-选择列事件');
      this.$refs.advanced.open(this.columns, this.currentTaskType);
    },
    /** 选择列更新事件 */
    saveColumnStatus(event) {
      let columns = event.data || []

      this.columns = []
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.$message.success(this.$t('common.base.saveSuccess'));
      })
    },
    /** 设置高级搜索展示列数 */
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },
    /** 表格选择操作 */
    handleSelection(selection) {
      let selected = [];

      selected = [
        ...this.multipleSelection.filter(s => {
          return !(this.taskPage.list.some(t => t.id === s.id));
        }),
        ...selection
      ];

      if(selected.length > MAXCHECK) {
        return this.$platform.alert(`最多只能选择${MAXCHECK}条数据`);
      }
      
      this.multipleSelection = selected;
    },
    /** 排序变化  */
    sortChange(option) {
      let {column, order, prop} = option;
      if(prop === 'customer') {
        prop = 'customerName';
      }
      if(column === null) {
        this.searchParams.sorts = [];
      }else{
        this.searchParams.sorts = [{
          property: prop.indexOf('field_') > -1 ? `attribute.${prop}` : prop,
          direction: order === 'ascending' ? 'ASC' : 'DESC',
        }]
      }
      
      this.search();
    },
    /** 清空选择框 */
    toggleSelection() {
      this.multipleSelection = [];
      this.$refs.multipleTable.clearSelection();
    },
    /** 页码跳转 */
    jump(page) {
      this.searchParams.page = page;
      this.taskPage.list = [];
      this.search();
    },
    /** 页大小改变 */
    handleSizeChange(pageSize) {
      this.searchParams.pageSize = pageSize;
      this.searchParams.page = 1;

      this.search();
    },
    /** 取消或订阅工单 */
    async toggleTaskSubscribe() {
      let action = this.hasSub ? TaskApi.taskUnSubscribe : TaskApi.taskSubscribe;
      let tip = this.hasSub ? '已取消订阅通知' : '已订阅通知';
      try {
        let res = await action({module:'taskAllot'});
        if(res.status == 0){
          this.$platform.alert(tip);
          this.hasSub = !this.hasSub;
        }else {
          this.$platform.alert(res.message);
        }
      } catch (error) {
        console.error(error);
      }
    },
    /** 指派工单操作 */
    async allotTask(row) {
      window.TDAPP && window.TDAPP.onEvent('pc：指派工单-指派事件');
      let confirm = await this.$platform.confirm('确定要指派吗？');
      if(!confirm) return
      
      let id = row.id;
      try {
        let res = await TaskApi.checkNotNullForCard({id, flow: 'allot'})
        if(res.status == 0) {
          let fromId = window.frameElement.getAttribute('id');

          openAccurateTab({
            type: PageRoutesTypeEnum.PageTaskView,
            key: row.id,
            titleKey: row.taskNo,
            params:  'noHistory=1&allot=true',
            fromId,
          });
        }else{
          this.$platform.alert(res.message);
        }
      } catch (error) {
        console.error(error);
      }
    },
    /** fetch工单配置 */
    async fetchTaskConfig() {
      try {
        let res = await TaskApi.getTaskConfig();
        this.taskConfig = res.taskConfig || new TaskConfig();
      } catch (error) {
        console.error(error);
      }
    },
    /** 打开地图派单弹窗 */
    allotMapDialogOpen() {
      this.$refs.allotMapDialog.openDialog();
    },
    /** 打开新建计划任务弹窗 */
    planTaskCreateDialogOpen() {
      if(this.multipleSelection.length < 1) {
        return this.$platform.alert('请先选择工单');
      }
      // 显示计划任务弹窗
      let planTaskEditFormEl = this.$refs.planTaskEditForm;
      if(planTaskEditFormEl) {
        this.fetchTaskConfig().then(() => {
          planTaskEditFormEl.toggle();
        })
      }
    },
    /** 批量创建计划任务 */
    submitWithPlanTask: _.debounce(async function(planTaskParams = {}) {
      let ids = this.multipleSelection.map(item => item.id);
      try {
        let params = {
          ids,
          planTask: planTaskParams
        };

        this.$refs.planTaskEditForm.togglePending(true);
        let res = await TaskApi.createBatchPlanTask(params);
        if(res.status == 1){
          this.$platform.alert(res.message);
        }else{
          this.$platform.alert(res.message);
          location.reload();
        }
      } catch (error) {
        console.error(error);
      } finally{
        this.$refs.planTaskEditForm.togglePending(false);
      }
    }, 250),
    /** 批量指派 */
    batchAllotDialogOpen() {
      if(this.multipleSelection.length < 1) {
        return this.$platform.alert('请选择需要批量指派的工单');
      }

      this.$refs.batchAllotDialog.openDialog(this.taskConfig);
    },

    // 获取列表当前的可滚动高度
    knowTableContainerHeight(){
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = window.getComputedStyle(this.$refs.tableHeaderContainer).height;
        header = header.replace('px', '');
        let do_ = window.getComputedStyle(this.$refs.tableDoContainer).height;
        do_ = do_.replace('px', '');
        let filter = window.getComputedStyle(this.$refs.tableFilterContainer).height;
        filter = filter.replace('px', '');
        let footer = window.getComputedStyle(this.$refs.tableFooterContainer).height;
        footer = footer.replace('px', '');
        console.log(window_, header, do_, footer, '11111');
        min = window_ - header * 1 - do_ * 1 - filter * 1 - footer * 1 - 24 - 24;
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    }
  },
  mounted() {
    this.fetchInitData();
    this.fetchTaskFields();
    this.fetchAllotList();
    this.fetchTaskConfig();
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
    })
    let that_ = this;
    window.onresize = _.debounce(()=>{
      that_.knowTableContainerHeight()
    }, 500)
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
  },
  components: {
    [BaseSearchDrawer.name]: BaseSearchDrawer,
    [BaseSearchPanel.name]: BaseSearchPanel,
    [BaseTableCell.name]: BaseTableCell,
    [BatchAllotDialog.name]: BatchAllotDialog,
    [PlanTaskEditForm.name]: PlanTaskEditForm,
    [AllotMapDialog.name]: AllotMapDialog
  }
}
</script>

<style lang="scss" scoped>
.search-input{
  width: 440px;
}

.search-input__append{
  @include backgroundColorImportant();
  color: #fff !important;
  border-radius: 0 4px 4px 0 !important;
}

.advanced-search-btn{
  @include fontColor;
}

.icon-dingyuetongzhiguanli{
  font-size: 14px;
  &.actived{
    color: #69b5f0;
  }
}

.el-input-group__append{
  border-radius: 0 4px 4px 0;
}
</style>